typedef and array of structs in c

chris (2008-11-01 11:38:21)
4806 views
1 replies
This example illustrates the use of typedef to define a datatype 'student' which is defined as a struct with a string pointer and two integer members. I then create an array of three 'student' structs, populate them all with values and then print their details out with the printf's at the end.

#include <stdio.h>
#include <string.h>

typedef struct{
	int age;
	int year;
	char* name;
} student ;

int main(int argc, char* argv[]){
	student p[3]; 

	p[0].name = "fred";
	p[0].age = 21;
	p[0].year = 2;
	p[1].name = "barney";
	p[1].age = 23;
	p[1].year = 2;
	p[2].name = "wilma";
	p[2].age = 24;
	p[2].year = 3;

	printf("n%s: age: %d, year: %dn",p[0].name,p[0].age,p[0].year);
	printf("n%s: age: %d, year: %dn",p[1].name,p[1].age,p[1].year);
	printf("n%s: age: %d, year: %dn",p[2].name,p[2].age,p[2].year);

	return 0;
}

If you compile and run this code, the output is as follows:

secondhalf-lm:junk clacy$ gcc structarray.c  -o structarray && ./structarray

fred: age: 21, year: 2

barney: age: 23, year: 2

wilma: age: 24, year: 3


christo
comment
chris
2008-11-08 00:07:30

declaring the array with malloc

Here is a version which uses malloc to reserve memory for the struct array - Note the extra flexibility provided by using malloc (as per the string example also in this channel).

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

typedef struct{
        int age;
        int year;
        char* name;
} student ;

int main(int argc, char* argv[]){
        student *p;   

        p = malloc(sizeof(student)*3);

        p[0].name = "fred";
        p[0].age = 21;
        p[0].year = 2;
        p[1].name = "barney";
        p[1].age = 23;
        p[1].year = 2;
        p[2].name = "wilma";
        p[2].age = 24;
        p[2].year = 3;

        printf("\n%s: age: %d, year: %d\n",p[0].name,p[0].age,p[0].year);
        printf("\n%s: age: %d, year: %d\n",p[1].name,p[1].age,p[1].year);
        printf("\n%s: age: %d, year: %d\n",p[2].name,p[2].age,p[2].year);

        return 0;
}

christo
reply icon